package com.ruoyi.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.admin.domain.Question;
import com.ruoyi.admin.domain.QuestionAnswer;
import com.ruoyi.admin.domain.UserAnswer;
import com.ruoyi.admin.mapper.UserAnswerMapper;
import com.ruoyi.admin.service.QuestionAnswerService;
import com.ruoyi.admin.service.QuestionService;
import com.ruoyi.admin.service.UserAnswerService;
import com.ruoyi.api.model.request.AnswerReq;
import com.ruoyi.api.model.response.AnswerHistoryResp;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * (UserAnswer)表服务实现类
 *
 * @author makejava
 * @since 2023-03-31 22:23:19
 */
@Service("userAnswerService")
public class UserAnswerServiceImpl extends ServiceImpl<UserAnswerMapper, UserAnswer> implements UserAnswerService {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private QuestionAnswerService questionAnswerService;

    @Override
    public int answer(AnswerReq answerReq){
        Question question = Optional.ofNullable(questionService.getById(answerReq.getQuestionId())).orElseThrow(() ->
                new ServiceException(StringUtils.format("未找到该questionId数据 = {}", answerReq.getQuestionId()))
        );
        UserAnswer userAnswer = new UserAnswer();
        userAnswer.setStudentId(SecurityUtils.getUserId());
        userAnswer.setUserAnswer(answerReq.getAnswer());
        userAnswer.setQuestionId(question.getId());
        userAnswer.setCreateBy(SecurityUtils.getUsername());
        userAnswer.setCreateTime(new Date());
        userAnswer.setDelFlag(0);
        userAnswer.setQuestionType(question.getQuestionType());
        if (question.getQuestionType() == 0 || question.getQuestionType() == 1) {
            QuestionAnswer questionAnswer = questionAnswerService.getOne(new LambdaQueryWrapper<QuestionAnswer>()
                    .eq(QuestionAnswer::getQuestionId, question.getId())
            );
            userAnswer.setQuestionAnswerId(questionAnswer.getId());
            userAnswer.setQuestionAnswer(questionAnswer.getAnswer());
            if (StringUtils.equals(questionAnswer.getAnswer(), answerReq.getAnswer())){
                userAnswer.setCorrectFlag(1);
            }else {
                userAnswer.setCorrectFlag(2);
            }
        }
        if (question.getQuestionType() == 2) {
            userAnswer.setSpokenUrl(answerReq.getSpokenUrl());
            userAnswer.setCorrectFlag(0);
        }
        if (question.getQuestionType() == 3) {
            userAnswer.setCorrectFlag(0);
        }
        this.save(userAnswer);
        return userAnswer.getCorrectFlag();
    }


    @Override
    public int paperAnswer(List<AnswerReq> answerReqList){
        List<Long> questionIdList = answerReqList.stream().map(AnswerReq::getQuestionId).collect(Collectors.toList());
        List<Question> questionList = questionService.list(new LambdaQueryWrapper<Question>()
                .in(Question::getId, questionIdList)
        );
        List<QuestionAnswer> questionAnswerList = questionAnswerService.list(new LambdaQueryWrapper<QuestionAnswer>()
                .in(QuestionAnswer::getQuestionId, questionIdList));
        List<UserAnswer> answerList = answerReqList.stream().map(answerReq -> {
            Question question = questionList.stream().filter(f -> f.getId().equals(answerReq.getQuestionId()))
                    .findFirst().orElseThrow(() ->
                            new ServiceException(StringUtils.format("未找到该questionId数据 = {}", answerReq.getQuestionId()))
                    );
            UserAnswer userAnswer = new UserAnswer();
            userAnswer.setPaperId(answerReq.getPaperId());
            userAnswer.setStudentId(SecurityUtils.getUserId());
            userAnswer.setUserAnswer(answerReq.getAnswer());
            userAnswer.setQuestionId(question.getId());
            userAnswer.setCreateBy(SecurityUtils.getUsername());
            userAnswer.setCreateTime(new Date());
            userAnswer.setDelFlag(0);
            userAnswer.setQuestionType(question.getQuestionType());
            if (question.getQuestionType() == 0 || question.getQuestionType() == 1) {
                QuestionAnswer questionAnswer = questionAnswerList.stream().filter(f -> f.getQuestionId().equals(question.getId()))
                        .findFirst().orElseThrow(() ->
                                new ServiceException(StringUtils.format("未找到该questionId数据 = {}", answerReq.getQuestionId()))
                        );

                userAnswer.setQuestionAnswerId(questionAnswer.getId());
                userAnswer.setQuestionAnswer(questionAnswer.getAnswer());
                if (StringUtils.equals(questionAnswer.getAnswer(), answerReq.getAnswer())) {
                    userAnswer.setCorrectFlag(1);
                } else {
                    userAnswer.setCorrectFlag(2);
                }
            }
            if (question.getQuestionType() == 2) {
                userAnswer.setSpokenUrl(answerReq.getSpokenUrl());
                userAnswer.setCorrectFlag(0);
            }
            if (question.getQuestionType() == 3) {
                userAnswer.setCorrectFlag(0);
            }
            return userAnswer;
        }).collect(Collectors.toList());
        int correctCount = (int) answerList.stream().map(UserAnswer::getCorrectFlag).filter(f -> f.equals(1)).count();
        this.saveBatch(answerList);
        return (correctCount / answerList.size()) * 100;
    }



    @Override
    public List<AnswerHistoryResp> answerHistory(UserAnswer userAnswer){
        List<AnswerHistoryResp> answerHistoryRespList = this.list(new LambdaQueryWrapper<UserAnswer>()
                .eq(Objects.nonNull(userAnswer.getQuestionId()), UserAnswer::getQuestionId, userAnswer.getQuestionId())
                .eq(Objects.nonNull(userAnswer.getStudentId()), UserAnswer::getStudentId, userAnswer.getStudentId())
                .eq(Objects.nonNull(userAnswer.getPaperId()), UserAnswer::getPaperId, userAnswer.getPaperId())
        ).stream().map(m -> {
            AnswerHistoryResp answerHistoryResp = new AnswerHistoryResp();
            answerHistoryResp.setId(m.getId());
            answerHistoryResp.setUserAnswer(m.getUserAnswer());
            answerHistoryResp.setQuestionAnswer(m.getQuestionAnswer());
            answerHistoryResp.setCorrectFlag(m.getCorrectFlag());
            answerHistoryResp.setCreateTime(m.getCreateTime());
            answerHistoryResp.setQuestionType(m.getQuestionType());
            answerHistoryResp.setSpokenUrl(m.getSpokenUrl());
            answerHistoryResp.setQuestionId(m.getQuestionId());
            return answerHistoryResp;
        }).collect(Collectors.toList());
        return answerHistoryRespList;
    }
}

